package com.topisv.tms.web.lpn;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import com.topisv.tms.costants.StorageConstants;
import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.lpn.Pallet;
import com.topisv.tms.entity.lpn.StorageOrder;
import com.topisv.tms.entity.lpn.VPalletInfo;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.repository.EdiOrderItemDao;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.lpn.PalletService;
import com.topisv.tms.service.lpn.StorageOrderService;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.tools.ExcelUtils;
import com.topisv.tms.tools.ExcelUtils3;
import com.topisv.tms.web.base.BaseDataTableController;
import com.topisv.tms.web.lpn.vo.PalletInfoVo;
import com.topisv.tms.web.lpn.vo.PalletOrderVo;
import com.topisv.tms.web.lpn.vo.PalletVo;

@Controller
@RequestMapping(value = "/v2_pallet")
public class PalletController extends BaseDataTableController {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    
    @Autowired
    private CustomersService customersService;
    
    @Autowired
    private AreaGroupService areaGroupService;
    
    @Autowired
    private PalletService palletService;
    
    @Autowired
    private WorkOrderService workOrderService;
    
    @Autowired
    private EdiOrderItemDao ediOrderItemDao;
    
    @Autowired
    private StorageOrderService storageOrderService;
    
    private static int cur_num ;
    
    /**
     * 装箱管理
     * 
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "v2_show")
    public String list(Model model, ServletRequest request) {
        // 当前用户关联的商家列表
        ShiroUser curUser = (ShiroUser)SecurityUtils.getSubject().getPrincipal();
        List<Customers> customerList = this.customersService.loadCustomerByAuthority(curUser);
        model.addAttribute("customerList", customerList);
        model.addAttribute("userType", curUser.userType);
        
        // 初始化仓库数据
        List<AreaGroup> warehouseList = this.areaGroupService.loadByWarehouseType("paiu");
        model.addAttribute("warehouseList", warehouseList);
        return "lpn/palletList";
    }
    
    /**
     * 装箱管理_page
     * 
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "page")
    public String page(Model model, ServletRequest request) {
        try {
            // 当前用户关联的商家列表
            ShiroUser curUser = (ShiroUser)SecurityUtils.getSubject().getPrincipal();
            List<Customers> customerList = this.customersService.loadCustomerByAuthority(curUser);
            model.addAttribute("customerList", customerList);
            model.addAttribute("userType", curUser.userType);
            // 初始化仓库数据
            List<AreaGroup> warehouseList = this.areaGroupService.loadByWarehouseType("paiu");
            model.addAttribute("warehouseList", warehouseList);
            
            Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
            String lpnNo = (String)param.get("lpnNo");
            String status = (String)param.get("status");
            model.addAttribute("_lpnNo", lpnNo);
            model.addAttribute("_status", status);
            String warehouseCode = (String)param.get("warehouseCode");
            model.addAttribute("_warehouseCode", warehouseCode);
            // 时间筛选
            String startTime = (String)param.get("startTime");
            String endTime = (String)param.get("endTime");
            model.addAttribute("_startTime", startTime);
            model.addAttribute("_endTime", endTime);
            Date startDate = null;
            Date endDate = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            PalletVo palletVo = new PalletVo();
            if (StringUtils.isNotEmpty(startTime)) {
                startDate = sdf.parse(startTime + " 00:00:00");
                palletVo.setStartTime(startDate);
            }
            if (StringUtils.isNotEmpty(endTime)) {
                endDate = sdf.parse(endTime + " 23:59:59");
                palletVo.setEndTime(endDate);
            }
            if (StringUtils.isNotBlank(lpnNo)) {
                palletVo.setLpnNo(lpnNo);
            }
            if (StringUtils.isNotBlank(status)) {
                palletVo.setStatus(Integer.parseInt(status));
            }
            if (StringUtils.isNotBlank(warehouseCode)) {
                palletVo.setWarehouseCode(warehouseCode);
            }
            // 托盘信息
            List<PalletVo> palletList = this.palletService.findAll(palletVo);
            model.addAttribute("palletList", palletList);
            
        } catch (Exception e) {
            logger.error("error", e);
        }
        return "lpn/palletList";
    }
    
    /**
     * 装箱信息查询
     * 
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "palletInfo")
    public String palletInfo(Model model, ServletRequest request) {
        // 初始化仓库数据
        List<AreaGroup> warehouseList = this.areaGroupService.loadByWarehouseType("paiu");
        model.addAttribute("warehouseList", warehouseList);
        
        return "lpn/palletInfo";
    }
    
    /**
     * 作业管理-装箱操作界面
     * 
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "handle_pallet")
    public String handle_pallet(Model model, ServletRequest request) {
        
        return "lpn/palletMgr";
    }
    
    /**
     * 跳转_新增托盘_页面
     * 
     * @param model
     * @return
     */
    @RequestMapping(value = "v2_create")
    public String createForm(Model model) {
        // 初始化仓库数据
        List<AreaGroup> warehouseList = this.areaGroupService.loadByWarehouseType("paiu");
        model.addAttribute("warehouseList", warehouseList);
        model.addAttribute("pallet", new Pallet());
        model.addAttribute("action", "v2_commit");
        cur_num = 0;
        return "lpn/palletForm";
    }
    
    /**
     * 保存_新增托盘
     * 
     * @param redirectAttributes
     * @param request
     * @return
     */
    @RequestMapping(value = "v2_commit", method = RequestMethod.POST)
    public String commit(Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        ShiroUser user = getShiroUser();
        String name = request.getParameter("name");
        String warehouseCode = request.getParameter("warehouseCode");
        String palletNum = request.getParameter("palletNum");
        int num = Integer.parseInt(request.getParameter("num"));
        List<Pallet> pallets = new ArrayList<Pallet>() ;
        if(cur_num == 0){
        	for (int i = 0; i < num; i++) {
                Pallet pallet = new Pallet();
                pallet.setWarehouseCode(warehouseCode);
                pallet.setName(name);
                pallet.setUserId(user.username);
                pallet.setPalletNum(warehouseCode + (i + Integer.parseInt(palletNum)));
                pallets.add(pallet) ;
            }
            this.palletService.savePallets(pallets) ;
        }
        model.addAttribute("_warehouseCode", warehouseCode);
        // 托盘信息
        PalletVo palletVo = new PalletVo();
        palletVo.setWarehouseCode(warehouseCode);
        palletVo.setName(name);
        List<PalletVo> palletList = this.palletService.findAll(palletVo);
        model.addAttribute("palletList", palletList);
        // 初始化仓库数据
        List<AreaGroup> warehouseList = this.areaGroupService.loadByWarehouseType("paiu");
        model.addAttribute("warehouseList", warehouseList);
        redirectAttributes.addFlashAttribute("message", "新增托盘成功");
        cur_num ++ ; 
        return "lpn/palletList";
    }
    
    /**
     * 批量禁用/批量释放
     * 
     * @param redirectAttributes
     * @param request
     * @return
     */
    @RequestMapping(value = "batchOperate", method = RequestMethod.POST)
    public void batchOperate(ServletRequest request, HttpServletResponse response) {
        JSONObject json = new JSONObject();
        try {
            int toStatus = Integer.parseInt(request.getParameter("toStatus"));
            String lpnNos = request.getParameter("lpnNos");
            List<String> lpnNoList = Arrays.asList(lpnNos.split(","));
            if (toStatus == StorageConstants.STATUS_FREE) {
                palletService.unloadOrdersByLpnNos(lpnNoList);// 根据LpnNo批量卸载托盘的订单(即:托盘与订单解绑)
            } else if(toStatus == StorageConstants.STATUS_DISABLE){
            	palletService.modifyStatusByLpns(toStatus, lpnNoList);//批量禁用托盘状态
            }
            json.put("status", "success");
        } catch (Exception e) {
            log.error("error", e);
            json.put("status", "error");
            json.put("content", e.getMessage());
        }
        writeJsonToResponse(json, response);
    }
    
    /**
     * 根据lpnNo获取pallet实体类
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "ajaxPalletByLpnNo")
    @ResponseBody
    public void ajaxGetNotice(@RequestParam String lpnNo, HttpServletResponse response) {
        JSONObject json = new JSONObject();
        try {
            Pallet pallet = this.palletService.getPalletByLpn(lpnNo);
            if (null == pallet) {// 没有此托盘
                json.put("status", 0);
            } else {
                if (pallet.getStatus() == 1) {// 空闲
                    json.put("status", 1);
                    json.put("content", pallet);
                } else if (pallet.getStatus() == 2) {// 使用中
                    json.put("status", 2);
                } else {// 禁用
                    json.put("status", 3);
                }
            }
        } catch (Exception e) {
            log.error("error", e);
        }
        writeJsonToResponse(json, response);
    }
    
    /**
     * 根据ordeno获取订单信息
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "ajaxOrderInfo")
    @ResponseBody
    public void ajaxOrderInfo(@RequestParam String ordeno, HttpServletResponse response) {
        JSONObject json = new JSONObject();
        try {
            Pallet pallet = this.palletService.getPalletByLpn(ordeno);
            if (null == pallet) {// 没有此托盘
                json.put("status", "error");
            } else {
                json.put("status", "success");
            }
        } catch (Exception e) {
            log.error("error", e);
        }
        writeJsonToResponse(json, response);
    }
    
    /**
     * ajax根据订单编号查询订单详情
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "ajaxCheckOrderInfo")
    public void ajaxCheckOrderInfo(ServletRequest request, HttpServletResponse response) {
        
        JSONObject json = new JSONObject();
        String msg = null;
        try {
            String orderno = request.getParameter("orderno");
            String lpnNo = request.getParameter("lpnNo");
            WorkOrder workOrder = this.workOrderService.loadByAnyOrderno(orderno);
            if (null != workOrder) {
                List<EdiOrderItem> orderItems = this.ediOrderItemDao.findByOrdeno(workOrder.getOrder().getOrdeno());
                if (null == workOrder.getOrder()) {
                    workOrder.getOrder().setOrderItems(orderItems);
                }
                if ("6".equals(workOrder.getStatus())) {
                    boolean flag = storageOrderService.checkOrderIsBind(orderno);
                    if (flag) {
                        msg = "binding";// 已绑定
                        json.put("workOrder", workOrder);
                    } else {
                        msg = "success";
                        json.put("workOrder", workOrder);
                    }
                    List<StorageOrder> soList = storageOrderService.getStorageOrderByLpnAndOrderNo(lpnNo, orderno) ;
                    if(null != soList&&soList.size()>0){
                    	msg = "binding2";// 已绑定
                        json.put("workOrder", workOrder);
                    }
                } else {
                    msg = "statuserror";// 非发货状态
                }
            } else {
                msg = "error"; // 无匹配的订单数据
            }
            json.put("msg", msg);
        } catch (Exception e) {
            
            logger.error("error", e);
            json.put("msg", "error");
        }
        writeJsonToResponse(json, response);
    }
    
    /**
     * 装箱_操作
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "handle_commit", method = RequestMethod.POST)
    public void handle_commit(ServletRequest request, HttpServletResponse response) {
        JSONObject json = new JSONObject();
        try {
            ShiroUser curUser = (ShiroUser)SecurityUtils.getSubject().getPrincipal();
            String ordernos_code = request.getParameter("ordernos_code");
            String lpnNo_code = request.getParameter("lpnNo_code");
            boolean flag = palletService.checkPalletFeeByLpn(lpnNo_code) ;
            List<StorageOrder> list = palletService.checkPalletFeeByorderNo(ordernos_code) ;
            if(null!=list&&list.size()>0){
            	StringBuffer sb = new StringBuffer("") ;
            	for(StorageOrder s:list){
            		sb.append(s.getOrderNo()).append(",") ;
            	}
            	json.put("msg", "orderused");
            	json.put("content", "订单已绑定："+sb.toString().substring(0,sb.length()-1)) ;
            }else{
            	if(flag){
                	if (StringUtils.isNotBlank(ordernos_code)) {
                        String[] orderno = ordernos_code.split(",");
                        List<StorageOrder> palletOrders = new ArrayList<StorageOrder>();
                        int batch = storageOrderService.getMaxBatchSeqByLpn(lpnNo_code) + 1;
                        for (int i = 0; i < orderno.length; i++) {
                            StorageOrder storageOrder = new StorageOrder();
                            storageOrder.setLpnNo(lpnNo_code);
                            storageOrder.setOrderNo(orderno[i]);
                            storageOrder.setUserId(curUser.username);
                            storageOrder.setBatchSeq(batch);
                            storageOrder.setCreateTime(new Date());
                            storageOrder.setStatus(StorageConstants.StorageOrder.STATUS_LOADED);
                            palletOrders.add(storageOrder);
                        }
                        int num = storageOrderService.loadedBatchPalletByLpn(lpnNo_code, palletOrders);
                        json.put("num", num);
                        json.put("msg", "success");
                        /**
                         *装箱操作成功后获取需要打印的数据
                         */
                        PalletInfoVo palletInfoVo = new PalletInfoVo();
                        palletInfoVo.setLpnNo(lpnNo_code);//设置lpn编码
                        palletInfoVo.setStatus(StorageConstants.StorageOrder.STATUS_LOADED);
                        //List<PalletOrderVo> palletOrderVoList = this.storageOrderService.finAll(palletOrderVo);
                        List<PalletInfoVo> palletInfoList = this.storageOrderService.finAll2(palletInfoVo);
                        if(null!=palletInfoList){
                        	palletInfoVo = palletInfoList.get(0) ;
                        }
                        palletInfoVo.setUsername(curUser.username);
                        json.put("palletInfoVo", palletInfoVo);
                        json.put("palletInfoList", palletInfoList);
                    } else {
                        json.put("msg", "error");
                    }
                }else{
                	json.put("msg", "used");
                }
            }
        } catch (Exception e) {
            logger.error("error", e);
            json.put("msg", "error");
        }
        writeJsonToResponse(json, response);
    }
    
    /**
     * 装箱信息查询
     * 
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "page2/{id}")
    public String page2(@PathVariable(value = "id") String id, Model model, ServletRequest request) {
        try {
            // 当前用户关联的商家列表
            ShiroUser curUser = (ShiroUser)SecurityUtils.getSubject().getPrincipal();
            List<Customers> customerList = this.customersService.loadCustomerByAuthority(curUser);
            model.addAttribute("customerList", customerList);
            model.addAttribute("userType", curUser.userType);
            // 初始化仓库数据
            List<AreaGroup> warehouseList = this.areaGroupService.loadByWarehouseType("paiu");
            model.addAttribute("warehouseList", warehouseList);
            
            Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
            String lpnNo = (String)param.get("lpnNo");
            if (!id.equals("info")) {
                lpnNo = id;
            }
            model.addAttribute("_lpnNo", lpnNo);
            String status = (String)param.get("status");
            model.addAttribute("_status", status);
            String warehouseCode = (String)param.get("warehouseCode");
            model.addAttribute("_warehouseCode", warehouseCode);
            String batchSeq = (String)param.get("batchSeq");
            model.addAttribute("_batchSeq", batchSeq);
            String orderNo = (String)param.get("orderNo");
            model.addAttribute("_orderNo", orderNo);
            // 时间筛选
            String startTime = (String)param.get("startTime");
            String endTime = (String)param.get("endTime");
            model.addAttribute("_startTime", startTime);
            model.addAttribute("_endTime", endTime);
            Date startDate = null;
            Date endDate = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            PalletOrderVo palletOrderVo = new PalletOrderVo();
            if (StringUtils.isNotEmpty(startTime)) {
                startDate = sdf.parse(startTime + " 00:00:00");
                palletOrderVo.setStartTime(startDate);
            }
            if (StringUtils.isNotEmpty(endTime)) {
                endDate = sdf.parse(endTime + " 23:59:59");
                palletOrderVo.setEndTime(endDate);
            }
            if (StringUtils.isNotBlank(lpnNo)) {
                palletOrderVo.setLpnNo(lpnNo);
            }
            if (StringUtils.isNotBlank(status)) {
                palletOrderVo.setStatus(Integer.parseInt(status));
            }
            if (StringUtils.isNotBlank(warehouseCode)) {
                palletOrderVo.setWarehouseCode(warehouseCode);
            }
            if (StringUtils.isNotBlank(batchSeq)) {
                palletOrderVo.setBatchSeq(Integer.parseInt(batchSeq));
            }
            if (StringUtils.isNotBlank(orderNo)) {
                palletOrderVo.setOrderNo(orderNo);
            }
            // 托盘信息查询
            List<PalletOrderVo> palletOrderList = this.storageOrderService.finAll(palletOrderVo);
            model.addAttribute("palletOrderList", palletOrderList);
        } catch (Exception e) {
            logger.error("error", e);
        }
        return "lpn/palletInfo";
    }
    
    /**
     * 导出装箱数据
     * 
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "exportExcel")
    public String exportExcel(Model model, ServletRequest request, ServletResponse response) {
        FileInputStream f = null;
        OutputStream output = null;
        try {
        	ShiroUser curUser = (ShiroUser)SecurityUtils.getSubject().getPrincipal();
            Date now = new Date();
            DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
            Map<String, Object> param = Servlets.getParametersStartingWith(request, "l");
            String lpnNo = (String)param.get("pnNo");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            PalletInfoVo palletInfoVo = new PalletInfoVo();
            palletInfoVo.setLpnNo(lpnNo);
            palletInfoVo.setStatus(StorageConstants.StorageOrder.STATUS_LOADED);
            //List<PalletOrderVo> palletOrderVoList = this.storageOrderService.finAll(palletOrderVo);
            List<PalletInfoVo> palletInfoList = this.storageOrderService.finAll2(palletInfoVo);
            /** 定义导出数据集合 */
            List<Object[]> list = new ArrayList<Object[]>();
            
            for (int i = 0; i < palletInfoList.size(); i++) {
                try {
                	PalletInfoVo storageOrder = palletInfoList.get(i);
                	if(i==0){
                		palletInfoVo.setWarehouseCode(storageOrder.getWarehouseCode());
                		palletInfoVo.setPalletNum(storageOrder.getPalletNum());
                		palletInfoVo.setCreateTime(storageOrder.getCreateTime());
                		palletInfoVo.setUsername(curUser.username);
                		palletInfoVo.setName(storageOrder.getName());
                	}
                    Object[] obj = {
                    		i+1,
                    		storageOrder.getOrderNo(),
                    		storageOrder.getSkuId(),
                    		storageOrder.getNam(),
                    		storageOrder.getQty(),
                    		storageOrder.getStatus() == 0 ? "解绑" : "绑定中",
                    		storageOrder.getBatchSeq(),
                    		storageOrder.getCreateTime() == null ? ""
                                    : sdf.format(storageOrder.getCreateTime()),
                        null};
                    list.add(obj);
                } catch (Exception e) {
                    
                    log.error("error", e);
                }
            }
            /** 导出数据 */
            String[] title = {"序号","订单编号","SKU","商品名称","数量", "装箱状态", "装箱批次", "装箱时间"};
            String filepath = "PalletInfo.xls";
            String title_page = "装箱信息表";
            ExcelUtils3.writeExcel(title, filepath, title_page, df.format(now), list,palletInfoVo); // 生成excel
            
            /** 把生成的excel文件读出字节返回给客户端 */
            ((HttpServletResponse)response).setHeader("Content-disposition",
                "attachment; filename=" + new String(filepath.getBytes("gb2312"), "ISO8859-1"));
            f = new FileInputStream(ExcelUtils.TEMPPATH + filepath);
            byte[] fb = new byte[f.available()];
            f.read(fb);
            ByteArrayInputStream bais = new ByteArrayInputStream(fb);
            output = ((HttpServletResponse)response).getOutputStream();
            int by = 0;
            while ((by = bais.read()) != -1) {
                output.write(by);
            }
            output.flush();
            
        } catch (Exception e) {
            return "error";
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    log.error("error", e);
                }
            }
            if (f != null) {
                try {
                    f.close();
                } catch (IOException e) {
                    log.error("error", e);
                }
            }
        }
        return null;
    }
    
    /**
     * 导出装箱信息
     * 
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "excelInfo")
    public String excelInfo(Model model, ServletRequest request, ServletResponse response) {
        FileInputStream f = null;
        OutputStream output = null;
        try {
        	ShiroUser curUser = (ShiroUser)SecurityUtils.getSubject().getPrincipal();
        	String username = curUser.username ;
            Date now = new Date();
            DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
            Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
            String lpnNo = (String)param.get("lpnNo");
            String status = (String)param.get("status");
            String warehouseCode = (String)param.get("warehouseCode");
            String batchSeq = (String)param.get("batchSeq");
            String orderNo = (String)param.get("orderNo");
            // 时间筛选
            String startTime = (String)param.get("startTime");
            String endTime = (String)param.get("endTime");
            Date startDate = null;
            Date endDate = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            PalletInfoVo palletInfoVo = new PalletInfoVo();
            if (StringUtils.isNotEmpty(startTime)) {
                startDate = sdf.parse(startTime + " 00:00:00");
                palletInfoVo.setStartTime(startDate);
            }
            if (StringUtils.isNotEmpty(endTime)) {
                endDate = sdf.parse(endTime + " 23:59:59");
                palletInfoVo.setEndTime(endDate);
            }
            if (StringUtils.isNotBlank(lpnNo)) {
            	palletInfoVo.setLpnNo(lpnNo);
            }
            if (StringUtils.isNotBlank(status)) {
            	palletInfoVo.setStatus(Integer.parseInt(status));
            }
            if (StringUtils.isNotBlank(warehouseCode)) {
            	palletInfoVo.setWarehouseCode(warehouseCode);
            }
            if (StringUtils.isNotBlank(batchSeq)) {
            	palletInfoVo.setBatchSeq(Integer.parseInt(batchSeq));
            }
            if (StringUtils.isNotBlank(orderNo)) {
            	palletInfoVo.setOrderNo(orderNo);
            }
            // 托盘信息查询
            List<PalletInfoVo> palletInfoList = this.storageOrderService.finAll2(palletInfoVo);
            /** 定义导出数据集合 */
            List<Object[]> list = new ArrayList<Object[]>();
            
            for (int i = 0; i < palletInfoList.size(); i++) {
                try {
                	PalletInfoVo storageOrder = palletInfoList.get(i);
                    Object[] obj = {
                    	storageOrder.getLpnNo(), 
                    	storageOrder.getName(), 
                    	storageOrder.getPalletNum(),
                        storageOrder.getOrderNo(), 
                        storageOrder.getSkuId(),
                        storageOrder.getNam(),
                        storageOrder.getQty(),
                        storageOrder.getStatus() == 0 ? "解绑" : "绑定中",
                        storageOrder.getBatchSeq(),
                        storageOrder.getCreateTime() == null ? "" : sdf.format(storageOrder.getCreateTime()),
                        storageOrder.getLast_update_time() == null ? ""
                            : sdf.format(storageOrder.getLast_update_time()),
                        null};
                    list.add(obj);
                } catch (Exception e) {
                    
                    log.error("error", e);
                }
            }
            
            /** 导出数据 */
            String[] title = {"LPN编码", "托盘名称", "托盘编码", "订单编号","SKU","商品名称","数量", "装箱状态", "装箱批次", "装箱时间", "卸载时间"};
            String filepath = "PalletOrderInfo.xls";
            String title_page = "托盘信息表";
            ExcelUtils3.writeExcel(title, filepath, title_page, df.format(now), list,sdf.format(new Date()),username); // 生成excel
            
            /** 把生成的excel文件读出字节返回给客户端 */
            ((HttpServletResponse)response).setHeader("Content-disposition",
                "attachment; filename=" + new String(filepath.getBytes("gb2312"), "ISO8859-1"));
            f = new FileInputStream(ExcelUtils.TEMPPATH + filepath);
            byte[] fb = new byte[f.available()];
            f.read(fb);
            ByteArrayInputStream bais = new ByteArrayInputStream(fb);
            output = ((HttpServletResponse)response).getOutputStream();
            int by = 0;
            while ((by = bais.read()) != -1) {
                output.write(by);
            }
            output.flush();
            
        } catch (Exception e) {
            return "error";
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    log.error("error", e);
                }
            }
            if (f != null) {
                try {
                    f.close();
                } catch (IOException e) {
                    log.error("error", e);
                }
            }
        }
        return null;
    }
}
